package com.Servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Servlet.Dao.usersEntity;
import com.User.Dao.Record;

@WebServlet("/readerBorrowBook")
public class readerBorrowBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] values = request.getParameterValues("checkBook");
		String userSno = request.getParameter("userSno");
		request.setAttribute("userSno", userSno);
		request.setAttribute("flag", "updateInfo");
		request.setAttribute("borrowFlag", "false");
		request.setAttribute("statusFlag", "true");
		if(values != null) {
			for(int i = 0; i < values.length; i++) {
				try {
					if(usersEntity.getHaveBook(userSno) < Integer.parseInt(usersEntity.enqury(userSno).getMaxBorrowBooks())) {
						usersEntity.updateBorrowBookToReader(userSno, values[i]);
						usersEntity.refolk(1, userSno);
						Date date = new Date();
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
						String createDate = dateFormat.format(date);
						Record re = new Record(values[i], userSno, createDate, null, "0");
						usersEntity.insertRecord(re);
						usersEntity.addClickSum(values[i]);
						request.setAttribute("borrowFlag", "ture");
					}else {
						request.setAttribute("statusFlag", "false");
					}
				} catch (ClassNotFoundException | SQLException | ParseException e) {
					System.out.println("The " + i + " book failed");
				}
			}
		}
		request.getRequestDispatcher("Main.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
